﻿@inherits ClientSectionCompontentBase

<MRow Class="pt-4">
    <MCol Md=6>
        <MRow>
            <MCol Md=12 Class="emphasis2--text">
                @T("IdentityResource")
            </MCol>
            @foreach (var identityScope in Dto.IdentityResources)
            {
                <MCol Md=6 Class="py-0">
                    <MCheckbox Disabled="ClientConsts.MandatoryResource.Contains(identityScope.Id)" @bind-Value="@identityScope.Selected" Label="@identityScope.DisplayValue" TValue="bool"/>
                </MCol>
            }
        </MRow>
    </MCol>
    <MDivider Vertical></MDivider>
    <MCol Md=6>
        <MRow>
            <MCol Md=12 Class="emphasis2--text">
                @T("ApiScope")
            </MCol>
            @foreach (var apiScope in Dto.ApiScopes)
            {
                <MCol Md=6 Class="py-0">
                    <MCheckbox @bind-Value="@apiScope.Selected" Label="@apiScope.DisplayValue" TValue="bool"/>
                </MCol>
            }
        </MRow>
    </MCol>
</MRow>

@code {
    [Parameter]
    public ClientScopesDto Dto { get; set; } = new();

    [Parameter]
    public EventCallback<ClientScopesDto> DtoChanged { get; set; }

    ClientScopesDto _dto = new();

    ApiScopeService ApiScopeService => AuthCaller.ApiScopeService;

    IdentityResourceService IdentityResourceService => AuthCaller.IdentityResourceService;

    protected override async Task OnParametersSetAsync()
    {
        if (_dto.GetHashCode()!=Dto.GetHashCode())
        {
            _dto = Dto;
            await LoadIdentityResources();
            await LoadApiScopes();
        }
        await base.OnParametersSetAsync();
    }

    private async Task LoadIdentityResources()
    {
        var identityResources = await IdentityResourceService.GetSelectAsync();
        Dto.IdentityResources = identityResources.Select(ir => new CheckItemDto<string>
            {
                DisplayValue = $"{ir.DisplayName} ({ir.Name})",
                Selected = Dto._AllowedScopes.Contains(ir.Name) || ClientConsts.MandatoryResource.Contains(ir.Name),
                Id = ir.Name
            }).ToList();
    }

    private async Task LoadApiScopes()
    {
        var apiScopes = await ApiScopeService.GetSelectAsync();
        Dto.ApiScopes = apiScopes.Select(ar => new CheckItemDto<string>
            {
                DisplayValue = $"{ar.DisplayName} ({ar.Name})",
                Selected = Dto._AllowedScopes.Contains(ar.Name),
                Id = ar.Name
            }).ToList();
    }
}
